package concurrent;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimedTask {

	public static void main(String[] args) {
		try {
			timedRun(new Runnable() {
				
				public void run() {
					int i = 0;
					while(!Thread.currentThread().isInterrupted()){
						i = i++;
					}
				}
			}, 10, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void timedRun(final Runnable r, long timeout, TimeUnit unit)
			throws InterruptedException {
		class RethrowableTask implements Runnable {
			private volatile Throwable t;

			public void run() {
				try {
					r.run();
				} catch (Throwable t) {
					this.t = t;
				}
			}

			public void rethrow() {
				if (t != null) {
					throw launderThrowable(t);
				}
			}

			public RuntimeException launderThrowable(Throwable t) {
				if (t instanceof RuntimeException)
					return (RuntimeException) t;
				else if (t instanceof Error)
					throw (Error) t;
				else
					throw new IllegalStateException("Not unchecked", t);
			}
		}

		RethrowableTask task = new RethrowableTask();
		final Thread taskThread = new Thread(task);
		taskThread.start();
		ScheduledExecutorService cancelExec = Executors
				.newScheduledThreadPool(1);
		cancelExec.schedule(new Runnable() {

			public void run() {
				taskThread.interrupt();
			}
		}, timeout, unit);
		cancelExec.shutdown();
		taskThread.join(unit.toMillis(timeout));
		task.rethrow();
	}

}
